<template>
  <a-drawer
    v-model:visible="visible"
    class="custom-class"
    :title="formState.id ? '编辑' : '新增'"
    :mask-closable="false"
    placement="right"
    width="500px"
    @close="close"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="formRules"
      :label-col="{ span: 3 }"
    >
      <a-form-item label="名称" name="name">
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item label="图片" name="avatar">
        <a-upload
          v-model:file-list="uploadState.fileList"
          name="files"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          :action="uploadState.actionUrl"
          :headers="uploadState.headers"
          :multiple="true"
          :maxCount="3"
          :before-upload="beforeUpload"
          @change="(e) => filesChange(e, setFileValue)"
        >
          <img
            v-if="formState.image"
            :src="uploadState.viewUrl + formState.image"
            alt="商品图片"
            class="inner-image"
          />
          <div v-else>
            <loading-outlined v-if="uploadState.loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">上传</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="类型" name="type">
        <a-radio-group v-model:value="formState.type">
          <a-radio value="1">普通商品</a-radio>
          <a-radio value="2">套餐</a-radio>
          <a-radio value="3">小料</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="原价">
        <a-input-number
          v-model:value="formState.originalPrice"
          :min="0"
          :precision="2"
          addon-after="元"
        />
      </a-form-item>
      <a-form-item label="优惠价" name="price">
        <a-input-number
          v-model:value="formState.price"
          :min="0"
          :precision="2"
          addon-after="元"
        />
      </a-form-item>
      <a-form-item label="上架" name="status">
        <a-switch
          v-model:checked="formState.status"
          checked-value="1"
          un-checked-value="0"
        />
      </a-form-item>
      <!-- <a-form-item label="库存量">
        <a-input v-model:value="formState.stock" />
      </a-form-item> -->
      <a-form-item label="规格">
        <a-select
          v-model:value="formState.sizeDictValue"
          placeholder="请选择"
          allow-clear
          :options="dictList"
          :field-names="{ label: 'name', value: 'value' }"
          style="width: 200px; text-align: left"
        >
        </a-select>
      </a-form-item>
      <a-form-item label="分类" name="cateId">
        <a-select
          v-model:value="formState.cateId"
          placeholder="请选择"
          allow-clear
          :options="cateList"
          :field-names="{ label: 'name', value: 'id' }"
          @change="cateChange"
          style="width: 200px; text-align: left"
        >
        </a-select>
      </a-form-item>
      <a-form-item label="简介">
        <a-textarea v-model:value="formState.summary" />
      </a-form-item>
      <a-form-item label="备注">
        <a-textarea v-model:value="formState.remark" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 21, offset: 3 }">
        <a-button
          type="primary"
          @click.prevent="onSubmit"
          style="margin-right: 12px"
        >
          保存
        </a-button>
        <a-button @click="close">取消</a-button>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>
<script setup>
import { useUpload } from "@/hooks/upload"
import { add, update } from "@/api/product"
import { selectList as selectDictList } from "@/api/dict"
import { ref, reactive, inject, onMounted, computed, watch } from "vue"

const cateList = inject("cateList")
const props = defineProps({
  visible: Boolean,
  current: Object,
})
const emit = defineEmits(["update:visible", "update:current", "query"])

const dictList = ref([])

const formRef = ref()
const formState = ref({
  id: "",
  name: "",
  avater: "",
  status: "0",
  cateId: "",
  cateName: "",
  originalPrice: 0,
  stock: 999,
  price: 0,
  sizeDictValue: "",
  type: "",
  summary: "",
  remark: "",
})
const formRules = reactive({
  name: [{ required: true, message: "商品名称不能为空!" }],
  type: [{ required: true, message: "商品类型不能为空!" }],
  price: [{ required: true, message: "商品价格不能为空!" }],
  status: [{ required: true, message: "商品状态不能为空!" }],
  cateId: [{ required: true, message: "商品分类不能为空!" }],
})

const { uploadState, beforeUpload, filesChange } = useUpload()

/** 获取字典 */
const getDictList = async (name) => {
  const { data, code } = await selectDictList({ name })
  if (code !== 200) return
  dictList.value = data
}
/** 选择分类完成后填充分类名称 */
const cateChange = (id) => {
  formState.value.cateName = cateList.value.find((e) => e.id === id).name
}

const setFileValue = (res) => {
  formState.value.image = res[0].url
  formState.value.imageThumb = res[0].url_thumb
  formState.value.remark = res[0].originalName
}
const close = () => {
  emit("update:current", null)
  emit("update:visible", false)
}

const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const func = (e) => (!formState.value.id ? add(e) : update(e))
      const { data, code } = await func(formState.value)
      if (code !== 300) return
      emit("query")
      close()
    })
    .catch((err) => {
      console.log("error", err)
    })
}

onMounted(() => {
  getDictList()
})

watch(
  () => props.current,
  (e) => {
    e ? Object.assign(formState.value, props.current) : (formState.value = {})
  },
  { deep: true }
)
</script>
<style lang="less" scoped></style>
